#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;
using std::weak_ptr;

void test()
{
    /* weak_ptr<int> wp(new int(20));//error */
    weak_ptr<int> wp;//ok
    {
        shared_ptr<int> sp(new int(10));
        wp = sp;
        cout << "sp.use_count() = " << sp.use_count() << endl;
        cout << "wp.use_count() = " << wp.use_count() << endl;

        cout << endl;
        bool flag = wp.expired();
        cout << "flag = " << flag << endl;

        cout << endl;
        shared_ptr<int> sp2 = wp.lock();
        if(sp2)
        {
            cout << "提升成功" << endl;
            cout << "*sp2 = " << *sp2 << endl;
        }
        else
        {
            cout << "提升失败，wp指向的空间已经被回收了" << endl;
        }
    }

    cout << "在离开作用域的时候" << endl;
    bool flag = wp.expired();
    cout << "flag = " << flag << endl;

    cout << endl;
    shared_ptr<int> sp2 = wp.lock();
    if(sp2)
    {
        cout << "提升成功" << endl;
        cout << "*sp2 = " << *sp2 << endl;
    }
    else
    {
        cout << "提升失败，wp指向的空间已经被回收了" << endl;
    }

}

int main(int argc, char **argv)
{
    test();
    return 0;
}

